package com.ruoyi.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.common.core.service.DictService;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.dept.domain.vo.BsInstrumentVo;
import com.ruoyi.dept.mapper.BsInstrumentMapper;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;
import com.ruoyi.base.domain.bo.SysMessageInfoBo;
import com.ruoyi.base.domain.vo.SysMessageInfoVo;
import com.ruoyi.base.domain.SysMessageInfo;
import com.ruoyi.base.mapper.SysMessageInfoMapper;
import com.ruoyi.base.service.ISysMessageInfoService;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 业务消息通知Service业务层处理
 *
 * @author kangyu
 * @date 2024-10-30
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Transactional
public class SysMessageInfoServiceImpl implements ISysMessageInfoService {

    private final SysMessageInfoMapper baseMapper;
    private final BsInstrumentMapper instrumentMapper;
    private final DictService dictService;

    /**
     * 查询业务消息通知
     */
    @Override
    public SysMessageInfoVo queryById(Long mId) {
        return baseMapper.selectVoById(mId);
    }

    /**
     * 查询业务消息通知列表
     */
    @Override
    public TableDataInfo<SysMessageInfoVo> queryPageList(SysMessageInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysMessageInfo> lqw = buildQueryWrapper(bo);
        Long deptId = LoginHelper.getDeptId();
        if (Objects.nonNull(deptId)) {
            lqw.eq(SysMessageInfo::getDeptId, deptId);
            lqw.orderByDesc(SysMessageInfo::getCreateTime);
        }
        lqw.eq(SysMessageInfo::getDelFlag, 0);
        Page<SysMessageInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(item -> {
            item.setMessageTypeLabel(dictService.getDictLabel("bs_message_type", item.getMessageType().toString()));
            item.setDegreeLabel(dictService.getDictLabel("bs_degree_type", item.getDegree().toString()));
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询业务消息通知列表
     */
    @Override
    public List<SysMessageInfoVo> queryList(SysMessageInfoBo bo) {
        LambdaQueryWrapper<SysMessageInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    public List<SysMessageInfoVo> queryListByBusinessId(SysMessageInfoBo bo) {
        LambdaQueryWrapper<SysMessageInfo> lqw = buildQueryWrapper(bo);
        lqw.eq(SysMessageInfo::getBusinessId, bo.getBusinessId());
        lqw.eq(SysMessageInfo::getDelFlag, 0);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysMessageInfo> buildQueryWrapper(SysMessageInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysMessageInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getMessageTitle()), SysMessageInfo::getMessageTitle, bo.getMessageTitle());
        lqw.eq(bo.getBusinessId() != null, SysMessageInfo::getBusinessId, bo.getBusinessId());
        lqw.eq(bo.getDeptId() != null, SysMessageInfo::getDeptId, bo.getDeptId());
        lqw.eq(StringUtils.isNotBlank(bo.getUserIds()), SysMessageInfo::getUserIds, bo.getUserIds());
        lqw.eq(bo.getMessageType() != null, SysMessageInfo::getMessageType, bo.getMessageType());
        lqw.eq(bo.getMessageContent() != null, SysMessageInfo::getMessageContent, bo.getMessageContent());
        lqw.eq(bo.getDegree() != null, SysMessageInfo::getDegree, bo.getDegree());
        lqw.eq(bo.getStatus() != null, SysMessageInfo::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增业务消息通知
     */
    @Override
    @DSTransactional
    public Boolean insertByBo(SysMessageInfoBo bo) {
        SysMessageInfo add = BeanUtil.toBean(bo, SysMessageInfo.class);
        validEntityBeforeSave(add);
        //针对实验室管理实验室仪器设备数据处理
        Boolean flag = false;
        if (Objects.nonNull(bo.getBusinessId())) {
            flag = FillExperimentalInstruments(add);
        }
        if (flag) {
            //达到预警阈值,插入
            baseMapper.insert(add);
            bo.setMId(add.getMId());
        }
        return flag;
    }

    /**
     * 修改业务消息通知
     */
    @Override
    @DSTransactional
    public Boolean updateByBo(SysMessageInfoBo bo) {
        SysMessageInfo update = BeanUtil.toBean(bo, SysMessageInfo.class);
        validEntityBeforeSave(update);
        Boolean flag = false;
        if (Objects.nonNull(bo.getBusinessId())) {
            flag = FillExperimentalInstruments(update);
            if (flag) {
                //修改
                baseMapper.updateById(update);
            }else {
                //未到预警阈值，删除
                baseMapper.deleteById(update.getMId());
            }
        }
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysMessageInfo entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 针对实验室管理实验室仪器设备数据处理
     */
    private Boolean FillExperimentalInstruments(SysMessageInfo entity) {
        //填充实验室仪器设备信息
        BsInstrumentVo bsInstrumentVo = instrumentMapper.selectVoById(entity.getBusinessId());
        if (Objects.nonNull(bsInstrumentVo.getEffectiveDate())) {
            entity.setDeptId(Long.valueOf(bsInstrumentVo.getDeptId()));
            entity.setMessageTitle(bsInstrumentVo.getInstruName() + "(" + bsInstrumentVo.getInstruCode() + ")");
            // 将 java.util.Date 转换为 LocalDateTime

            LocalDateTime effectiveDate = bsInstrumentVo.getEffectiveDate().toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
            LocalDateTime now = LocalDateTime.now();
            long days = ChronoUnit.DAYS.between(effectiveDate, now);
            if (days < 0 && days >= -15) {
                entity.setMessageContent(
                    DateUtils.parseDateToStr("yyyy-MM-dd", bsInstrumentVo.getEffectiveDate())
                        + "(" + Math.abs(days) + "天过期)");
                //提醒
                entity.setDegree(1L);
                entity.setMessageType(2L);
                return true;
            } else if (days == 0) {
                entity.setMessageContent(
                    DateUtils.parseDateToStr("yyyy-MM-dd", bsInstrumentVo.getEffectiveDate())
                        + "(已过期)");
                //紧急
                entity.setDegree(2L);
                entity.setMessageType(2L);
                return true;
            } else if (days > 0) {
                entity.setMessageContent(
                    DateUtils.parseDateToStr("yyyy-MM-dd", bsInstrumentVo.getEffectiveDate())
                        + "(已过期" + Math.abs(days) + "天)");
                //紧急
                entity.setDegree(2L);
                entity.setMessageType(2L);
                return true;
            }
        }
        return false;
    }

    /**
     * 批量删除业务消息通知
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    public void deleteWithValidByBusinessIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        List<SysMessageInfo> list = baseMapper.selectList(new LambdaQueryWrapper<SysMessageInfo>().eq(SysMessageInfo::getDelFlag, 0).in(SysMessageInfo::getBusinessId, ids));
        if (CollectionUtils.isNotEmpty(list)) {
            ids = list.stream().map(SysMessageInfo::getMId).collect(Collectors.toList());
            baseMapper.deleteBatchIds(ids);
        }
    }
}
